package com.joycessh.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	private static SessionFactory sessionFactory = null;	
	//配置文件中注册的是映射文件,调用Configuration()方法：
	  private static Configuration configuration = new Configuration();

	//配置文件中注册的是注释映射PO类,调用AnnotationConfiguration()方法：
	//private static Configuration configuration = new AnnotationConfiguration();   

	    //构造方法	
		public HibernateUtil()
		{
			initHibernate();
		}    

	    //初始化sessionFactory实例：
		public static synchronized void initHibernate() throws HibernateException
		{    
	    	if(sessionFactory == null)
	    	try {
	    			configuration.configure();   //启动hibernate    			
	    			sessionFactory = configuration.buildSessionFactory();       		
	    		} catch (HibernateException he) {
	    			System.err.println(" Error Creating SessionFactory ");
	    			throw he;
	    		}    		
	    }	
		
	    //重新创建SessionFactory实例
		public static void rebuildSessionFactory() throws HibernateException
		{
			try {
				configuration.configure();
				sessionFactory = configuration.buildSessionFactory();
			} catch (HibernateException he) {
				System.err.println(" Error Creating SessionFactory ");
				throw he;
			}
		}
		
	    //获取Session实例
		public static Session getSession() throws HibernateException {
			if (sessionFactory == null) 
			{
				rebuildSessionFactory();
			}
			Session session = sessionFactory.openSession();
	        return session;
	    }
		
		public void closeSessionFactory() throws HibernateException
		{
			sessionFactory.close();
		}

}
